package cn.satoken.common;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.support.SFunction;

/**
 * <h3>saToken</h3>
 * <p></p>
 *
 * @author gdw
 * @since 2025-03-27 10:58:01
 */
public class ValueValid {
    /**
        * 确认数据库字段值有效（通用）
        *
        * @param <V> 待验证值的类型
        * @param valueToCheck 待验证的值
        * @param columnExtractor 实体类属性提取函数
        * @param queryExecutor 单条数据查询执行器
        * @param errorMessage 异常提示信息模板
        */
    public static <T, R, V> void ensureColumnValueValid(V valueToCheck, SFunction<T, R> columnExtractor, SFunction<LambdaQueryWrapper<T>, T> queryExecutor, String errorMessage) {
        if (valueToCheck == null) return;
        LambdaQueryWrapper<T> wrapper = new LambdaQueryWrapper<>();
        wrapper.select(columnExtractor);
        wrapper.eq(columnExtractor, valueToCheck);
        T entity = queryExecutor.apply(wrapper);
        if (entity != null)
            throw new RuntimeException(String.format(errorMessage, valueToCheck));
    }
    /**
     * 确认数据库字段值有值
     *
     * @param <V> 待验证值的类型
     * @param valueToCheck 待验证的值
     * @param columnExtractor 实体类属性提取函数
     * @param queryExecutor 单条数据查询执行器
     */
    public static <T, R, V> Boolean ensureColumnValueValid(V valueToCheck, SFunction<T, R> columnExtractor, SFunction<LambdaQueryWrapper<T>, T> queryExecutor) {
        if (valueToCheck == null) return false;
        LambdaQueryWrapper<T> wrapper = new LambdaQueryWrapper<>();
        wrapper.select(columnExtractor);
        wrapper.eq(columnExtractor, valueToCheck);
        T entity = queryExecutor.apply(wrapper);
        if (entity != null) {
            return true;
        }else {
            return false;
        }
    }
}
